﻿<h1>Methods in Go</h1>

<p>
Go supports some object-orient programming features.
Method is one of these features.
This article will introduce method related concepts in Go.
</p>

<h3>Method Declarations</h3>

<div>
In Go, we can (explicitly) declare a method for type <code>T</code> and <code>*T</code>,
where <code>T</code> must satisfy 4 conditions:
<ol>
<li>
	<code>T</code> must be a <a href="type-system-overview.html#non-defined-type">defined type</a>;
</li>
<li>
	<code>T</code> must be defined in the same package as the method declaration;
</li>
<li>
	<code>T</code> must not be a pointer type;
</li>
<li>
	<code>T</code> must not be an interface type.
	Interface types will be explained in
	<a href="interface.html">the next article</a>.
</li>
</ol>

<p>
Type <code>T</code> and <code>*T</code> are called the receiver type of the respective methods declared for them.
Type <code>T</code> is called the receiver base types of all methods declared for both type <code>T</code> and <code>*T</code>.
</p>

<p>
Note, we can also declare methods for <a href="type-system-overview.html#type-alias">type aliases</a>
of the <code>T</code> and <code>*T</code> types specified above.
The effect is the same as declaring methods for the <code>T</code>
and <code>*T</code> types themselves.
</p>

<p>
If a method is declared for a type, we can say the type has (or owns) the method.
</p>

From the above listed conditions, we will get the conclusions that
we can never (explicitly) declare methods for:
<ul>
<li>
	built-in basic types, such as <code>int</code> and <code>string</code>,
	for we can't declare methods in the <code>builtin</code> standard package.
</li>
<li>
	interface types. But an interface type can own methods.
	Please read <a href="interface.html">the next article</a> for details.
</li>
<li>
	<a href="type-system-overview.html#non-defined-type">non-defined types</a>
	except the pointer types with the form <code>*T</code> which are described above.
</li>
</ul>

<p>
A method declaration is similar to a function declaration,
but it has an extra parameter declaration part.
The extra parameter part can contain one and only one parameter of the receiver type of the method.
The only one parameter is called a receiver parameter of the method declaration.
The receiver parameter must be enclosed in a <code>()</code>
and declared between the <code>func</code> keyword and the method name.
</p>

Here are some method declaration examples:
<pre class="line-numbers"><code class="language-go">// Age and int are two distinct types. We
// can't declare methods for int and *int,
// but can for Age and *Age.
type Age int
func (age Age) LargerThan(a Age) bool {
	return age > a
}
func (age *Age) Increase() {
	*age++
}

// Receiver of custom defined function type.
type FilterFunc func(in int) bool
func (ff FilterFunc) Filte(in int) bool {
	return ff(in)
}

// Receiver of custom defined map type.
type StringSet map[string]struct{}
func (ss StringSet) Has(key string) bool {
	_, present := ss[key]
	return present
}
func (ss StringSet) Add(key string) {
	ss[key] = struct{}{}
}
func (ss StringSet) Remove(key string) {
	delete(ss, key)
}

// Receiver of custom defined struct type.
type Book struct {
	pages int
}
func (b Book) Pages() int {
	return b.pages
}
func (b *Book) SetPages(pages int) {
	b.pages = pages
}
</code></pre>

<p>
From the above examples, we know that the receiver base types
not only can be struct types, but also can be
other kinds of types, such as basic types and container types,
as long as the receiver base types satisfy the 4 conditions listed above.
</p>

<p>
In some other programming languages,
the receiver parameter names are always the implicit <code>this</code>,
which is not a recommended identifier for receiver parameter names in Go.
</p>

<p>
The receiver of type <code>*T</code> is called <b><i>pointer receiver</i></b>,
non-pointer receivers are called <b><i>value receivers</i></b>.
Personally, I don't recommend to view the terminology <b><i>pointer</i></b>
as an opposite of the terminology <b><i>value</i></b>,
because pointer values are just special values.
But, I am not against using the pointer receiver and value receiver terminologies here.
The reason will be explained below.
</p>
</div>

<p>
Method names can be the blank identifier <code>_</code>.
A type can have multiple methods with the blank identifier as name.
But such methods can never be called.
Only exported methods can be called from other packages.
Method calls will be introduced in a later section.
</p>

<a class="anchor" id="method-as-function"></a>
<h3>Each Method Corresponds to an Implicit Function</h3>

<div>
For each method declaration, compiler will declare a corresponding implicit function for it.
For the last two methods declared for type <code>Book</code> and type <code>*Book</code>
in the last example in the last section,
two following functions are implicitly declared by compiler:

<pre class="line-numbers"><code class="language-go">func Book.Pages(b Book) int {
	// The body is the same as the Pages method.
	return b.pages
}

func (*Book).SetPages(b *Book, pages int) {
	// The body is the same as the SetPages method.
	b.pages = pages
}
</code></pre>

<p>
In each of the two implicit function declarations, the receiver parameter
is removed from its corresponding method declaration and inserted
into the normal parameter list as the first one.
The function bodies of the two implicitly declared functions
is the same as their corresponding method explicit bodies.
</p>

The implicit function names, <code>Book.Pages</code> and <code>(*Book).SetPages</code>,
are both of the form <code>TypeDenotation.MethodName</code>.
As identifiers in Go can't contain the period special characters,
the two implicit function names are not legal identifiers,
so the two functions can't be declared explicitly.
They can only be declared by compilers implicitly,
but they can be called in user code:

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type Book struct {
	pages int
}
func (b Book) Pages() int {
	return b.pages
}
func (b *Book) SetPages(pages int) {
	b.pages = pages
}

func main() {
	var book Book
	// Call the two implicit declared functions.
	(*Book).SetPages(&book, 123)
	fmt.Println(Book.Pages(book)) // 123
}
</code></pre>

<p>
</p>

In fact, compilers not only declare the two implicit functions,
they also rewrite the two corresponding explicit declared methods
to let the two methods call the two implicit functions in the method bodies
(at least, we can think this happens), just like the following code shows:

<pre class="line-numbers"><code class="language-go">func (b Book) Pages() int {
	return Book.pages(b)
}
func (b *Book) SetPages(pages int) {
	(*Book).SetPages(b, pages)
}
</code></pre>

<p>
</p>

</div>

<a class="anchor" id="implicit-pointer-methods"></a>
<h3>Implicit Methods With Pointer Receivers</h3>

<div>
For each method declared for value receiver type <code>T</code>,
a corresponding method with the same name will be
implicitly declared by compiler for type <code>*T</code>.
By the example above, the <code>Pages</code> method is declared for type <code>Book</code>,
so compilers will implicitly declare a method with the same name <code>Pages</code>
for type <code>*Book</code>. The same method name contains one line of code,
which is a call to the implicit function <code>Book.Pages</code> introduced above.

<pre class="line-numbers"><code class="language-go">func (b *Book) Pages() int {
	return Book.Pages(*b)
}
</code></pre>

<p>
This is why I don't reject the use the value receiver terminology
(as the opposite of the pointer receiver terminology).
After all, when we expliclty declare a method for a non-pointer type,
in fact two methods are declared, the explicit one is for the non-pointer type
and the implicit one is for the corresponding pointer type.
</p>

As mentioned at the last section, for each declared method,
compilers will also declare a corresponding implicit function for it.
So for the implicitly declared method, the following implicit function is
declared by compiler.

<pre class="line-numbers"><code class="language-go">func (*Book).Pages(b *Book) int {
	return Book.Pages(*b)
}
</code></pre>

<p>
In other words, for each explicitly declared method with a value receiver,
two implicit functions and one implicit method will also be declared at the same time.
</p>
</div>

<a class="anchor" id="method-set"></a>
<h3>Method Prototypes and Method Sets</h3>

<div>

<p>
A method prototype can be viewed as a
<a href="function.html#prototype">function prototype</a>
without the <code>func</code> keyword.
We can view each method declaration is composed of the <code>func</code> keyword,
a receiver parameter declaration, a method prototype and a method (function) body.
</p>

For example, the method prototypes of the <code>Pages</code> and
<code>SetPages</code> methods shown above are

<pre class="line-numbers"><code class="language-go">Pages() int
SetPages(pages int)
</code></pre>

<p>
</p>

<p>
Each type has a method set.
The method set of a non-interface type is composed of all the method prototypes
of the methods declared, either explicitly or implicitly, for the type,
except the ones whose names are the blank identifier <code>_</code>.
Interface types will be explained in
<a href="interface.html">the next article</a>.
</p>

For example, the method sets of the <code>Book</code> type shown in the
previous sections is
<pre class="line-numbers"><code class="language-go">Pages() int
</code></pre>

and the method set of the <code>*Book</code> type is

<pre class="line-numbers"><code class="language-go">Pages() int
SetPages(pages int)
</code></pre>

<p>
</p>

<p>
The order of the method prototypes in a method set is not important for the method set.
</p>

<p>
For a method set, if every method prototype in it is also in another method set,
then we say the former method set is a subset of the latter one, and the latter one is a superset of the former one.
If two method sets are subsets (or supersets) of each other,
then we say the two method sets are identical.
</p>

<p>
Given a type <code>T</code>, assume it is neither a pointer type nor an
interface type, for <a href="#implicit-pointer-methods">the reason</a>
mentioned in the last section, the method set of a type <code>T</code> is always
a subset of the method set of type <code>*T</code>.
For example, the method set of the <code>Book</code> type shown above is a
subset of the method set of the <code>*Book</code> type.
</p>

<p>
Please note, <b>non-exported method names, which start with lower-case letters,
from different packages will be always viewed as two different method names,
even if the two method names are the same in literal.</b>
</p>

<p>
Method sets play an important role in the polymorphism feature of Go.
About polymorphism, please read <a href="interface.html">the next article</a>
(interfaces in Go) for details.
</p>

The method sets of the following types are always blank:
<ul>
<li>built-in basic types.</li>
<li>defined pointer types.</li>
<li>pointer types whose base types are interface or pointer types.</li>
<li>undefined array, slice, map, function and channel types.</li>
</ul>

<p>
</p>

</div>

<a class="anchor" id="call"></a>
<h3>Method Values and Method Calls</h3>

<p>
Methods are special functions in fact.
Methods are often called member functions.
When a type owns a method, each value of the type will own an immutable member of function type.
The member name is the same as the method name and the type of the member is the same as
the function declared with the form of the method declaration but without the receiver part.
</p>

<p>
A method call is just a call to such a member function.
For a value <code>v</code>, its method <code>m</code> can be represented
with the selector form <code>v.m</code>, which is a function value.
</p>

<div>
An example containing some method calls:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type Book struct {
	pages int
}

func (b Book) Pages() int {
	return b.pages
}

func (b *Book) SetPages(pages int) {
	b.pages = pages
}

func main() {
	var book Book

	fmt.Printf("%T \n", book.Pages)       // func() int
	fmt.Printf("%T \n", (&book).SetPages) // func(int)
	// &book has an implicit method.
	fmt.Printf("%T \n", (&book).Pages) // func() int

	// Call the three methods.
	(&book).SetPages(123)
	book.SetPages(123) // equivalent to the last line
	fmt.Println(book.Pages())    // 123
	fmt.Println((&book).Pages()) // 123
}
</code></pre>

<p>
<!--
In the above example, the value <code>book</code> is called the base value of both
the receiver arguments of the <code>Pages</code> and <code>SetPages</code> method calls.
-->
</p>

<p><i>
(Different from C language, there is not the <code>-&gt;</code> operator in Go
to call methods with pointer receivers,
so <code>(&amp;book)-&gt;SetPages(123)</code> is illegal in Go.)
</i></p>

<p>
Wait! Why does the line <code>book.SetPages(123)</code> in the above example compile okay?
After all, the method <code>SetPages</code> is not declared for the <code>Book</code> type.
Ah, this is just a syntactic sugar to make programming convenient.
This sugar only works for addressable value receivers.
Compiler will automatically take the address of the addressable <code>book</code> value
when it is passed as the receiver argument of a <code>SetPages</code> method call.
</p>

<!--
<pre class="line-numbers"><code class="language-go"> ...

// Function results are not addressable in Go.
func MakeBook() Book {
	return Book{}
}

func main() {
	var book Book
	book.SetPages(123) // <=> (&book).SetPages(123)
	fmt.Println(book.Pages()) // 123

	// error: function return results are not addressable.
	MakeBook().SetPages(123)
}
</code></pre>
-->

<!--
In fact, the method value <code>book.Pages</code>
can be viewed as a closure returned by:
<pre class="line-numbers"><code class="language-go">func() func() int {
	return func() int {
		Book.Pages(b)
	}
}(book)
</code></pre>

and the method value <code>(&book).SetPages</code>
can be viewed as closures returned by:
<pre class="line-numbers"><code class="language-go">func (b *Book) func(int) {
	return func(pages int) {
		(*Book).SetPages(b, pages)
	}
}(&book)
</code></pre>
-->

<p>
As above just mentioned, when a method is declared for a type,
each value of the type will own a member function.
Zero values are not exceptions, whether or not the zero values
of the types are represented by <code>nil</code>.
</p>

Example:
<pre class="line-numbers"><code class="language-go">package main

type StringSet map[string]struct{}
func (ss StringSet) Has(key string) bool {
	// Never panic here, even if ss is nil.
	_, present := ss[key]
	return present
}

type Age int
func (age *Age) IsNil() bool {
	return age == nil
}
func (age *Age) Increase() {
	*age++ // If age is a nil pointer, then
	       // dereferencing it will panic.
}

func main() {
	_ = (StringSet(nil)).Has   // will not panic
	_ = ((*Age)(nil)).IsNil    // will not panic
	_ = ((*Age)(nil)).Increase // will not panic

	_ = (StringSet(nil)).Has("key") // will not panic
	_ = ((*Age)(nil)).IsNil()       // will not panic

	// This following line will panic. But the
	// panic is not caused by invoking the method.
	// It is caused by the nil pointer dereference
	// within the method body.
	((*Age)(nil)).Increase()
}
</code></pre>
</div>

<h3>Receiver Arguments Are Passed by Copy</h3>

<p>
Same as general function arguments,
the receiver arguments are also passed by copy.
So, the modifications on the <a href="value-part.html">direct part</a>
of a receiver argument in a method call will not be reflected to
the outside of the method.
</p>

<div>
An example:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type Book struct {
	pages int
}

func (b Book) SetPages(pages int) {
	b.pages = pages
}

func main() {
	var b Book
	b.SetPages(123)
	fmt.Println(b.pages) // 0
}
</code></pre>

<p>
</p>

Another example:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type Book struct {
	pages int
}

type Books []Book

func (books Books) Modify() {
	// Modifications on the underlying part of
	// the receiver will be reflected to outside
	// of the method.
	books[0].pages = 500
	// Modifications on the direct part of the
	// receiver will not be reflected to outside
	// of the method.
	books = append(books, Book{789})
}

func main() {
	var books = Books{{123}, {456}}
	books.Modify()
	fmt.Println(books) // [{500} {456}]
}
</code></pre>

<p>
</p>

Some off topic, if the two lines in the orders of
the above <code>Modify</code> method are exchanged, then both of the modifications
will not be reflected to outside of the method body.
<pre class="line-numbers"><code class="language-go">func (books Books) Modify() {
	books = append(books, Book{789})
	books[0].pages = 500
}

func main() {
	var books = Books{{123}, {456}}
	books.Modify()
	fmt.Println(books) // [{123} {456}]
}
</code></pre>

<p>
The reason here is that the <code>append</code> call will allocate a new
memory block to store the elements of the copy of the passed slice receiver argument.
The allocation will not reflect to the passed slice receiver argument itself.
</p>

To make both of the modifications be reflected to outside of the method body,
the receiver of the method must be a pointer one.
<pre class="line-numbers"><code class="language-go">func (books *Books) Modify() {
	*books = append(*books, Book{789})
	(*books)[0].pages = 500
}

func main() {
	var books = Books{{123}, {456}}
	books.Modify()
	fmt.Println(books) // [{500} {456} {789}]
}
</code></pre>
</div>

<h3>Should a Method Be Declared With Pointer Receiver or Value Receiver?</h3>

<p>
Firstly, from the last section,
we know that sometimes we must declare methods with pointer receivers.
</p>

<p>
In fact, we can always declare methods with pointer receivers without any logic problems.
It is just a matter of program performance that sometimes it is better to declare methods
with value receivers.
</p>

<div>
For the cases value receivers and pointer receivers are both acceptable,
here are some factors needed to be considered to make decisions.
<ul>
<li>
	Too many pointer copies may cause heavier workload for garbage collector.
</li>
<li>
	If the size of a value receiver type is large,
	then the receiver argument copy cost may be not negligible.
	Pointer types are all <a href="value-copy-cost.html">small-size</a> types.
</li>
<li>
	Declaring methods of both value receivers and pointer receivers
	for the same base type is more likely to cause data races
	if the declared methods are called concurrently in multiple goroutines.
</li>
<li>
	Values of the types in the <code>sync</code> standard package
	should not be copied, so defining methods with value receivers for
	struct types which <a href="type-embedding.html">embedding</a>
	the types in the <code>sync</code> standard package is problematic.
</li>
</ul>
</div>

<p>
If it is hard to make a decision whether
a method should use a pointer receiver or a value receiver,
then just choose the pointer receiver way.
</p>
